<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="available" >
        <el-select v-model="queryParams.available" @keyup.enter.native="handleQuery">
          <el-option value="" label="全部">全部</el-option>
          <el-option value="1" label="启用">启用</el-option>
          <el-option value="0" label="停用">停用</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:Customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:Customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:Customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:Customer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="CustomerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column label="编号" align="center" prop="code"  width="160"/>
      <el-table-column label="名称" align="center" prop="name"  width="110"/>
      <el-table-column label="状态" align="center" prop="available" width="110">
      <template slot-scope="scope">
        <span>{{ scope.row.available == 1 ? "启用" : "停用" }}</span>
      </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy"  width="120"/>
      <el-table-column label="修改时间" align="center" prop="updateTime"  width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="description" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="getShow(scope.row)"
            v-hasPermi="['system:Customer:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:Customer:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:Customer:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1150px" append-to-body>
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="助记码" prop="mnemonicCode">
          <el-input v-model="form.mnemonicCode" placeholder="请输入助记码"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入联系电话"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" style="width: 230px" />
        </el-form-item>
        <el-form-item label="邮编" prop="zipCode">
          <el-input v-model="form.zipCode" placeholder="请输入邮编"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="传真" prop="fax">
          <el-input v-model="form.fax" placeholder="请输入传真" style="width: 230px" />
        </el-form-item>
<!--        <el-form-item label="地区ID" prop="cityId">-->
<!--          <el-input v-model="form.cityId" placeholder="请输入地区ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="地区" prop="cityId">
          <el-cascader style="width: 230px"
             v-model="value"
             :options="options1"
             :props="{
             value:'id',
             label:'name',
             children:'children',expandTrigger: 'hover'}"
             clearable
             @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"  style="width: 230px"/>
        </el-form-item>
        <template v-if="form.id != null">
          <el-form-item label="结账方式" prop="settleType">
            <el-select v-model="form.settleType" @keyup.enter.native="handleQuery" disabled   style="width: 230px">
              <el-option :value="1" label="任意指定">任意指定</el-option>
              <el-option :value="0" label="货到付款">货到付款</el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-if="form.id == null">
          <el-form-item label="结账方式" prop="settleType">
            <el-select v-model="form.settleType" @keyup.enter.native="handleQuery"  style="width: 230px">
              <el-option :value="1" label="任意指定">任意指定</el-option>
              <el-option :value="0" label="货到付款">货到付款</el-option>
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="taxIdentifyNo">
          <el-input v-model="form.taxIdentifyNo" placeholder="请输入纳税人识别号"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户银行"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="户名" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入户名"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="银行账号" prop="accountNo">
          <el-input v-model="form.accountNo" placeholder="请输入银行账号"  style="width: 230px"/>
        </el-form-item>
        <el-form-item label="状态" prop="available" v-if="form.id != null">
          <el-select v-model="form.available" @keyup.enter.native="handleQuery"  style="width: 230px">
            <el-option :value="1" label="启用">启用</el-option>
            <el-option :value="0" label="停用">停用</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" placeholder="请输入备注"  style="width: 230px"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看" :visible.sync="open1" width="1150px" append-to-body>
      <el-descriptions :column="2" border :data="haseShow">
        <el-descriptions-item label="编号">{{haseShow.code}}</el-descriptions-item>
        <el-descriptions-item label="名称">{{haseShow.name}}</el-descriptions-item>
        <el-descriptions-item label="助记码">{{haseShow.mnemonicCode}}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{haseShow.contact}}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{haseShow.telephone}}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{haseShow.email}}</el-descriptions-item>
        <el-descriptions-item label="邮编">{{haseShow.zipCode}}</el-descriptions-item>
        <el-descriptions-item label="传真">{{haseShow.fax}}</el-descriptions-item>
        <el-descriptions-item label="地区">{{haseShow.cityId}}</el-descriptions-item>
        <el-descriptions-item label="地址">{{haseShow.address}}</el-descriptions-item>
        <el-descriptions-item label="结账方式">{{haseShow.settleType == 1 ? "任意指定":"货到付款"}}</el-descriptions-item>
        <el-descriptions-item label="统一社会信用代码">{{haseShow.creditCode}}</el-descriptions-item>
        <el-descriptions-item label="纳税人识别号">{{haseShow.taxIdentifyNo}}</el-descriptions-item>
        <el-descriptions-item label="开户银行">{{haseShow.bankName}}</el-descriptions-item>
        <el-descriptions-item label="户名">{{haseShow.accountName}}</el-descriptions-item>
        <el-descriptions-item label="银行账户">{{haseShow.accountNo}}</el-descriptions-item>
        <el-descriptions-item label="状态">{{haseShow.available  == 1 ? "启用" : "停用"}}</el-descriptions-item>
        <el-descriptions-item label="备注">{{haseShow.description}}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/system/Customer";
import { listCity, listCity1 } from '@/api/system/City'
import { getStoreCenterInfo } from '@/api/system/StoreCenterInfo'

export default {
  name: "Customer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //编号
      codeNum:null,
      // 客户表格数据
      CustomerList: [],

      value: [],
      options1:[],
      //查看
      haseShow:[],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        available: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        mnemonicCode: [
          { required: true, message: "助记码不能为空", trigger: "blur" }
        ],
        settleType: [
          { required: true, message: "结算方式不能为空", trigger: "change" }
        ],
        available: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    //级联下拉框
    this.getCityList();
    this.getCityList1();
  },
  methods: {
    //级联下拉框
    getCityList() {
      this.loading = true;
      listCity(this.queryParams).then(response => {
        this.options1 = response.rows;
      });
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.CustomerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCityList1() {
      this.loading = true;
      listCity1(this.queryParams).then(response => {
        this.options2 = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        mnemonicCode: null,
        contact: null,
        telephone: null,
        email: null,
        zipCode: null,
        fax: null,
        cityId: null,
        address: null,
        settleType: null,
        creditCode: null,
        taxIdentifyNo: null,
        bankName: null,
        accountName: null,
        accountNo: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      //级联下拉框
      this.value=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    getShow(row) {
      this.loading = true;
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.haseShow = response.data;
        if (this.haseShow.cityId != null){
          var fenge = this.haseShow.cityId.split("/");
          for (let j = 0;j<fenge.length;j++){
            for (let k = 0;k<this.options2.length;k++){
              if (fenge[j] == this.options2[k].id){
                fenge[j] = this.options2[k].name;
              }
            }
          }
          fenge=fenge.join('/');
          this.haseShow.cityId  = fenge;
        }
        this.open1=true;
        this.loading = false;
        this.title = "查看";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        //级联下拉框
        if(this.form.cityId != null){
          const codes = this.form.cityId.split("/");
          this.value = codes;
        }
        this.codeNum = this.form.code;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            //级联下拉框
            const str = this.value;
            var str1 = "";
            for (var i = 0; i < str.length; i++) {
              if (i == str.length - 1) {
                str1 += str[i];
                break;
              }
              str1 += str[i] + "/";
            }
            this.form.cityId = str1;
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            //级联下拉框
            const str = this.value;
            var str1 = "";
            for (var i = 0; i < str.length; i++) {
              if (i == str.length - 1) {
                str1 += str[i];
                break;
              }
              str1 += str[i] + "/";
            }
            this.form.cityId = str1;
            var orderCode = getOrderCode(this.CustomerList);
            this.form.code = orderCode;
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(function() {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/Customer/export', {
        ...this.queryParams
      }, `Customer_${new Date().getTime()}.xlsx`)
    }
  }
};

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="KH";
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(2,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      console.log(list);
      let listCode=list[i].code.slice(2,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
